////////////////////////////////////////////////////////////////////////////////
//
//  http://www.17nce.com
//  Copyright 2011-2012 
//  All Rights Reserved.
//
//  gtshao@sina.cn  2010-12-24
//
////////////////////////////////////////////////////////////////////////////////
package com.nce.view{
	import com.nce.ApplicationFacade;
	import com.nce.model.LsnProxy;
	import com.nce.view.components.Bkw;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.TextEvent;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.containers.TabNavigator;
	import mx.controls.SWFLoader;
	import mx.utils.StringUtil;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	/**
	 * 
	 */
	public class BkwMediator extends Mediator{
		
		public static const NAME:String = "BkwMediator";
		
		public static const TAB_TEACHER_CLASS:int = 0;
		public static const TAB_STUDY_WORD:int = 1;
		public static const TAB_STUDY_SENTENCE:int = 2;
		public static const TAB_SUBMIT_QUESTION:int = 3;
		
		private var _channel:SoundChannel;
		private var _crtReadCount:int;
		private var _notUseTimer:Boolean = true;
		
		public function BkwMediator(viewComponent:Object=null)
		{
			super(NAME,viewComponent);
			
		}
		
		
		override public function onRegister():void
		{
			bkw.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			bkw.addEventListener(Bkw.NEXT_SENTENCE,onNextSentence);
			bkw.addEventListener(Bkw.PRE_SENTENCE,onPreSentence);
			bkw.addEventListener(Bkw.READ,onRead);
			bkw.addEventListener(Bkw.MERGE,onMerge);
			
			bkw.addEventListener(Bkw.BACK_ETIME,onBackEtime);
			bkw.addEventListener(Bkw.BACK_STC_TIME,onBackStcTime);
			bkw.addEventListener(Bkw.MOVE_ETIME,onMoveEtime);
			bkw.addEventListener(Bkw.MOVE_STC_TIME,onMoveStcTime);
			bkw.addEventListener(Bkw.MOVE_LESSON_TIME,onMoveLessonTime);
			bkw.addEventListener(Bkw.BACK_LESSON_TIME,onBackLessonTime);
			
			bkw.addEventListener(Bkw.CHANGE_CLASS,onChangeClass);
			bkw.addEventListener(Bkw.CHANGE_LESSON,onChangeLesson);
			bkw.addEventListener(Bkw.CHANGE_TERM,onChangeTerm);
			bkw.addEventListener(Bkw.CHANGE_TAB,onChangeTab);
			bkw.addEventListener(Bkw.CHANGE_SOUND,onChangeSound);
			
			bkw.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			//bkw.focusManager.setFocus(bkw.userTextTA);
			
			
			
		}
		
		private function onKeyDown(evt:KeyboardEvent):void{
			if(evt.ctrlKey){
				switch (evt.keyCode){
					case 37:{
						playPre();
					}
					case 39:{
						playNext();
					}
					case 13:{
						play();
					}
				}
					
			}
			trace(evt.keyCode);
			trace(evt.charCode);
			trace(evt.ctrlKey);
		}
		
		private function resetUserText():void{
			bkw.userTextTA.text="";
			bkw.errorCount=0;
			bkw.userTextInfoTxt.text="输入课文.";
		}
		
		private function onUserInputText(evt:Event):void{
			var userTextStr:String = bkw.userTextTA.text;
			var crtEnTextStr:String = bkw.lesson[bkw.index].en_text;
			crtEnTextStr = StringUtil.trim(crtEnTextStr.split("^").join(""));
			
			trace(crtEnTextStr);
			if(crtEnTextStr.substr(0,userTextStr.length) != userTextStr){
				bkw.errorCount++;
				bkw.userTextTA.text = userTextStr.substr(0,userTextStr.length-1);
			}			
			if(userTextStr==crtEnTextStr){
				if(bkw.errorCount==0){
					bkw.userTextInfoTxt.text="太神奇了,我碰到牛人了,一次都没有错呢.";
				}else if(bkw.errorCount<3){
					bkw.userTextInfoTxt.text="还不错了,多加加油离牛人不远了.";
				}else if(bkw.errorCount<11){
					bkw.userTextInfoTxt.text="要多加油哦.";
				}else if(bkw.errorCount>10){
					bkw.userTextInfoTxt.text="你要打破记录了,只可惜是错误的记录.";
				}
				
			}
		}
		
		private function onChangeSound(evt:Event):void{
			createSound();
			
		}
		
		private function createSound():void{
			var lesson:int = int(bkw.lessonCbB.selectedIndex);
			var term:int = bkw.termCbB.selectedIndex;
			//第一册的特殊处理
			if(term==0){
				lesson = ++lesson * 2 -1;
			}else{
				++lesson;
			}
			if(bkw.useUsCBX.selected){
				bkw.sound = new Sound(new URLRequest("http://www.ncewx.com/Public/usnce"+(++term)+"/"+(lesson)+".mp3"));
			}else{
				bkw.sound = new Sound(new URLRequest("http://www.ncewx.com/Public/nce"+(++term)+"/"+(lesson)+".mp3"));
			}
		}
		private function onChangeTab(evt:Event):void{
			initNavTab();
		}
		
		private function onChangeTerm(evt:Event):void{
			var lsnProxy:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			var term:int = bkw.termCbB.selectedIndex+1;
			lsnProxy.getLessons(term);			
		}
		
		private function initNavTab():void{
			if(bkw.nav.selectedIndex == TAB_TEACHER_CLASS){
				bkw.ff.source = "http://www.ncewx.com/Public/html/nce.php?yksid="+getCrtLsnYksid();
				trace('getSelectedVideo');
				
			}else if(bkw.nav.selectedIndex == TAB_STUDY_WORD){
				trace('getSelectedWords');
			}else if(bkw.nav.selectedIndex== TAB_STUDY_SENTENCE){
				getSelectedLesson();
				bkw.userTextTA.addEventListener(Event.CHANGE,onUserInputText);	
			}else if(bkw.nav.selectedIndex == TAB_SUBMIT_QUESTION){
				trace("init submitQuestion");
			}		
		}
		
		private function getCrtLsnYksid():String{
			return bkw.lessonCbB.selectedItem.youkuid;
		}
		
		private function onChangeLesson(evt:Event):void{
			initNavTab();
		}
		
		private function getSelectedLesson():void{
			var lsnProxy:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			lsnProxy.getLsn(bkw.lessonCbB.selectedIndex+1,bkw.termCbB.selectedIndex+1);
		}
		
		private function onChangeClass(evt:Event):void{
//			bkw.nceclass.unloadAndStop();
//			bkw.ms.removeChild(bkw.nceclass);
//			bkw.nceclass = new SWFLoader();
//			bkw.nceclass.load("http://player.youku.com/player.php/sid/XMTM5OTcwODk2/v.swf");
//			//bkw.nceclass.addEventListener(Event.COMPLETE,onOk);
//			bkw.nceclass.maintainAspectRatio = false;
//			bkw.nceclass.scaleContent = true;
//			bkw.nceclass.width=320;
//			bkw.nceclass.height=240;
//			
//			bkw.ms.addChild(bkw.nceclass);
		}
		
		private function onOk(e:Event):void
		{
			e.target.content.width=1000;
			e.target.content.height=750;
		}
		
		
		override public function listNotificationInterests():Array
		{
			return [ ApplicationFacade.CHANGE_LESSON,ApplicationFacade.GET_LESSONS ];		
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch ( notification.getName() )
			{
				
				case ApplicationFacade.CHANGE_LESSON:
					bkw.lesson = notification.getBody() as Array;
					bkw.index = 0;					
				    createSound();					
					play();
					break;
				case ApplicationFacade.GET_LESSONS:
					bkw.lessons = notification.getBody() as Array;	
					initNavTab();
					break;
			}
		}
		
		//----------------------------------界面功能部分-------------------------------------
		
		private function onEnterFrame(ent:Event):void{
			
			//如过有开始播放,并且没有使用Timer来延迟播放
			if(_channel && _notUseTimer){
				var endtime:int = 0;
				if(bkw.useUsCBX.selected){
					endtime = bkw.lesson[bkw.index].usetime;
				}else{
					endtime = bkw.lesson[bkw.index].etime;
				}
				if(_channel.position > endtime){
					stopPlay();					
				}
			}
		}
		
		private function stopPlay():void{
			_channel.stop();					
			bkw.readerBtn.enabled = true;
			if(_crtReadCount>0){
			  play();
			}else{
				if(bkw.autoPlayCBX.selected){
					playNext();
				}
			}
		}
		
		private function play():void{
			if(bkw.interval > 0 && _crtReadCount != bkw.readCount){
				trace(bkw.interval*1000);
				var _timer:Timer = new Timer(bkw.interval*1000,1); 
				_timer.addEventListener(TimerEvent.TIMER, onTimerPlay);	
				_timer.start();
				_notUseTimer = false; //设置为不使用Timer播放模式
				
				return;
			}else{
				realplay();
			}
		}
		
		private function realplay():void{
			//不是第一遍,先停止原来的播放
			if(_channel){
				_channel.stop();
			}
			_notUseTimer = true;
			trace("_crtReadCount--:"+_crtReadCount--);
			var starttime:int = 0;
			if(bkw.useUsCBX.selected){
				starttime = bkw.lesson[bkw.index].usstime;
			}else{
				starttime = bkw.lesson[bkw.index].stime;
			}
			_channel = bkw.sound.play(starttime);
			bkw.readerBtn.enabled = false;
		}
		
		private function playNext():void{
			//不是最后一句
			if(bkw.lesson.length-1>bkw.index){
				_crtReadCount = bkw.readCount;
				bkw.index++;
				resetUserText();
				play();
			}
		}
		
		private function playPre():void{
			if(bkw.index>0){
				resetUserText();
				bkw.index--;
				play();
			}
		}
		
		private function onTimerPlay(ent:Event):void{			
			realplay();	
		}
		
		private function onRead(ent:Event):void{			
			play();			
		}
		
		
		
		
		private function onPreSentence(ent:Event):void{
			playPre();
		}
		
		private function onNextSentence(ent:Event):void{
			playNext();
		}
		
		private function get bkw():Bkw
		{
			return viewComponent as Bkw;
		}	
		
		//----------------------------校对时间部分-------------------------------------
		
		private function onMerge(ent:Event):void{			
			//保存当前位置
			var tmpIdx:int = bkw.index; 
			
			//把这一句的内容合并到上一句
			var lsnProxy:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;					
			lsnProxy.merge(bkw.lesson[bkw.index-1].id,bkw.lesson[bkw.index].id);
			
			//遍历余下语句,把每句的idx前移一位			
			for(var i:int = bkw.index; i < bkw.lesson.length; i++){
				lsnProxy.decreaseIdx(bkw.lesson[i].id,bkw.lesson[i].idx-1);
			}
			//还原当前位置
			bkw.index = tmpIdx;			
		}
		
		
		private function onBackLessonTime(evt:Event):void{
			//保存当前位置
			var tmpIdx:int = bkw.index; 
			//遍历课文,依次修改时间
			for(var i:int = 0; i < bkw.lesson.length; i++){
				bkw.index = i;
				if(bkw.useUsCBX.selected){
					trace("前移US");
					moveUsStime(-500);
					moveUsEtime(-500);
				}else{
					trace("前移EN");
					moveStime(-500);
					moveEtime(-500);
				}
			}
			//还原当前位置
			bkw.index = tmpIdx;
			
		}
		
		private function onMoveLessonTime(evt:Event):void{
			//保存当前位置
			var tmpIdx:int = bkw.index; 
			//遍历课文,依次修改时间
			for(var i:int = 0; i < bkw.lesson.length; i++){
				bkw.index = i;
				if(bkw.useUsCBX.selected){
					trace("后移US");
					moveUsStime(500);
					moveUsEtime(500)
				}else{
					trace("后移EN");
					moveStime(500);
					moveEtime(500);
				}
			}
			//还原当前位置
			bkw.index = tmpIdx;
			
		}
		
		//句子前移
		private function onBackStcTime(evt:Event):void{
			if(bkw.useUsCBX.selected){
				moveUsStime(-500);
				moveUsEtime(-500);
			}else{
				moveStime(-500);
				moveEtime(-500);
			}
			
		}
		
		//句子后移
		private function onMoveStcTime(evt:Event):void{
			if(bkw.useUsCBX.selected){
				moveUsStime(500);
				moveUsEtime(500)
			}else{
				moveStime(500);
				moveEtime(500);
			}
			
		}
		
		//结尾前移
		private function onBackEtime(evt:Event):void{
			if(bkw.useUsCBX.selected){
				moveUsEtime(-500);	
			}else{
				moveEtime(-500);	
			}
			
			if(bkw.index<(bkw.lesson.length-1)){
				//保存当前位置
				var tmpIdx:int = bkw.index; 
				var usgap:int =   bkw.lesson[bkw.index].usetime - bkw.lesson[bkw.index+1].usstime;
				var engap:int =   bkw.lesson[bkw.index].etime - bkw.lesson[bkw.index+1].stime;
				
				//遍历课文,依次修改时间
				for(var i:int = tmpIdx+1; i < bkw.lesson.length; i++){
					bkw.index = i;
					if(bkw.useUsCBX.selected){
						trace("前移US "+usgap);
						moveUsStime(usgap);
						moveUsEtime(usgap);
					}else{
						trace("前移EN");
						moveStime(engap);
						moveEtime(engap);
					}
				}
				//还原当前位置
				bkw.index = tmpIdx;
			}
			
		}
		
		//结尾后移
		private function onMoveEtime(evt:Event):void{
			if(bkw.useUsCBX.selected){
				moveUsEtime(500);	
			}else{
				moveEtime(500);		
			}
			if(bkw.index<(bkw.lesson.length-1)){
				//保存当前位置
				var tmpIdx:int = bkw.index; 
				var usgap:int =   bkw.lesson[bkw.index].usetime - bkw.lesson[bkw.index+1].usstime;
				var engap:int =   bkw.lesson[bkw.index].etime - bkw.lesson[bkw.index+1].stime;
				
				//遍历课文,依次修改时间
				for(var i:int = tmpIdx+1; i < bkw.lesson.length; i++){
					bkw.index = i;
					if(bkw.useUsCBX.selected){
						moveUsStime(usgap);
						moveUsEtime(usgap);
					}else{
						moveStime(engap);
						moveEtime(engap);
					}
				}
				//还原当前位置
				bkw.index = tmpIdx;
			}
			
		}
		
		private function moveEtime(mt:int):void{
			var lsnProxy1:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			var ti:int = int(bkw.lesson[bkw.index].etime);
			bkw.lesson[bkw.index].etime = ti+mt;
			trace(bkw.lesson[bkw.index].etime );
			lsnProxy1.setSentenceEtime(bkw.lesson[bkw.index].id,int(bkw.lesson[bkw.index].etime));
		}
		
		private function moveStime(mt:int):void{
			var lsnProxy:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			var ti:int = int(bkw.lesson[bkw.index].stime);
			bkw.lesson[bkw.index].stime = ti+mt;
			trace(bkw.lesson[bkw.index].stime );
			lsnProxy.setSentenceStime(bkw.lesson[bkw.index].id,int(bkw.lesson[bkw.index].stime));
		}
		
		private function moveUsEtime(mt:int):void{
			var lsnProxy1:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			var ti:int = int(bkw.lesson[bkw.index].usetime);
			bkw.lesson[bkw.index].usetime = ti+mt;
			trace(bkw.lesson[bkw.index].usetime );
			lsnProxy1.setSentenceUsEtime(bkw.lesson[bkw.index].id,int(bkw.lesson[bkw.index].usetime));
		}
		
		private function moveUsStime(mt:int):void{
			var lsnProxy:LsnProxy = facade.retrieveProxy(LsnProxy.NAME) as LsnProxy;
			var ti:int = int(bkw.lesson[bkw.index].usstime);
			bkw.lesson[bkw.index].usstime = ti+mt;
			trace(bkw.lesson[bkw.index].usstime );
			lsnProxy.setSentenceUsStime(bkw.lesson[bkw.index].id,int(bkw.lesson[bkw.index].usstime));
		}
		
		
	}
}